import 'package:dio/dio.dart';
import 'package:get/get_state_manager/get_state_manager.dart';
import 'package:my_app/app/config/http_config.dart';
import 'package:my_app/app/core/api_interceptor/api_error_interceptor.dart';
import 'package:my_app/app/core/api_interceptor/api_request_interceptor.dart';
import 'package:my_app/app/core/api_interceptor/api_response_interceptor.dart';

/// api_service.dart
///
/// Created by fuchuanwei on Tue Feb 21 2023.
///
///Description: APi 服务
///
class ApiService extends GetxService {
  late Dio _dio;

  @override
  void onInit() {
    super.onInit();
    BaseOptions options = BaseOptions(
      baseUrl: HttpConfig.baseUrl,
      responseType: HttpConfig.responseType,
      connectTimeout: HttpConfig.connectTimeout,
      receiveTimeout: HttpConfig.receiveTimeout,
    );
    //初始化Dio
    _dio = Dio(options);
    //添加请求拦截器
    addRequestInterceptor(ApiRequestInterceptor());
    //添加响应拦截器
    addResponseInterceptor(ApiResponseInterceptor());
    //添加错误拦截器
    addErrorInterceptor(ApiErrorInterceptor());
    //添加日志拦截器
    addLogInterceptor();
  }

  // 添加请求拦截器
  void addRequestInterceptor(
    Interceptor onRequest,
  ) {
    _dio.interceptors.add(onRequest);
  }

  // 添加响应拦截器
  void addResponseInterceptor(
    Interceptor onResponse,
  ) {
    _dio.interceptors.add(onResponse);
  }

  //添加错误拦截器
  void addErrorInterceptor(
    Interceptor onError,
  ) {
    _dio.interceptors.add(onError);
  }

  //添加日志拦截器
  void addLogInterceptor() {
    _dio.interceptors.add(LogInterceptor(
      requestBody: true,
      responseHeader: false,
      responseBody: true,
    ));
  }

  // 发送 GET 请求
  Future<Response<T>> get<T>(
    String path, {
    Map<String, dynamic>? queryParameters,
    Options? options,
  }) {
    return _dio.get<T>(
      path,
      queryParameters: queryParameters,
      options: options,
    );
  }

  // 发送 POST 请求
  Future<Response<T>> post<T>(
    String path, {
    dynamic data,
    Options? options,
  }) {
    return _dio.post<T>(
      path,
      data: data,
      options: options,
    );
  }

  // 发送 PUT 请求
  Future<Response<T>> put<T>(
    String path, {
    dynamic data,
    Options? options,
  }) {
    return _dio.put<T>(
      path,
      data: data,
      options: options,
    );
  }

  // 发送 DELETE 请求
  Future<Response<T>> delete<T>(
    String path, {
    dynamic data,
    Options? options,
  }) {
    return _dio.delete<T>(
      path,
      data: data,
      options: options,
    );
  }
}
